// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
var app = angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngCordova', 'underscore', 'tabSlideBox'])
.factory('sessionInjector', function() {
    var sessionInjector = {
        request: function(config) {
            if(config.url.indexOf('?')>-1&&window.localStorage.isLogin=='true'){
                var memberId_ = window.localStorage.memberId!=null?window.localStorage.memberId:'';
                var token_ = window.localStorage.token!=null?window.localStorage.token:'';
                config.url=config.url+'&token_='+token_+'&memberId_='+memberId_;
            }
            return config;
        }
    };
    return sessionInjector;
})
.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('sessionInjector');
}])
.run(function($ionicPlatform,$http,userService) {
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady()
    {
        screen.lockOrientation('portrait');
        //window.screen.lockOrientation('portrait');
    }

    $ionicPlatform.ready(function() {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
            cordova.plugins.Keyboard.disableScroll(true);//IOS
        }
        if (window.StatusBar) {
            // org.apache.cordova.statusbar required
            StatusBar.styleDefault();
        }
        window.localStorage.base_url="http://www.tr008.com/rongtouServer";
        //window.localStorage.base_url="http://192.168.0.103:8089/rongtouServer";
        //window.localStorage.base_url="http://192.168.1.135:8080/rongtouServer";

        //进系统判断登录是否过期，后台设置默认是一周时间
        if(window.localStorage.isLogin=='true'){
            $http.get(window.localStorage.base_url+'/app/member/login?phone='+window.localStorage.phone+'&token='+window.localStorage.token).success(function(req){
              if(req.code=='0'){
                //正常，没有过期，没有改密码
              }else{
                //过期或者改过密码，
                console.log(req);
                userService.setLogout();
              }
            }).error(function(res){
              console.log(res);
            })
        }
    });
/*
    //物理返回按钮控制&双击退出应用
    $ionicPlatform.registerBackButtonAction(function (e) {
        //判断处于哪个页面时双击退出
        if ($location.path() == '/web/counsel/index' || $location.path() == '/web/product/index' || $location.path() == '/web/activity/index' || $location.path() == '/web/user/index' || $location.path() == '/web/more') {
            if ($rootScope.backButtonPressedOnceToExit) {
                ionic.Platform.exitApp();
            } else {
                $rootScope.backButtonPressedOnceToExit = true;
                $cordovaToast.showShortBottom('再按一次退出系统');
                setTimeout(function () {
                    $rootScope.backButtonPressedOnceToExit = false;
                }, 2000);
            }
        }else if ($ionicHistory.backView()) {
            if ($cordovaKeyboard.isVisible()) {
                $cordovaKeyboard.close();
            } else {
                $ionicHistory.goBack();
            }
        }
        else {
            $rootScope.backButtonPressedOnceToExit = true;
            $cordovaToast.showShortBottom('再按一次退出系统');
            setTimeout(function () {
                $rootScope.backButtonPressedOnceToExit = false;
            }, 2000);
        }
        e.preventDefault();
        return false;
    }, 101);*/
})
.run(['$ionicPlatform', function ($ionicPlatform) {

            $ionicPlatform.ready(function () {
                var u = navigator.userAgent;
                //console.log(navigator.userAgent);
                var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
                var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
                if(isAndroid){
                    /* android 开始*/
                    if (window.cordova && window.cordova.plugins.Keyboard) {
                        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                    }
                    if (window.StatusBar) {
                        // org.apache.cordova.statusbar required
                        StatusBar.styleDefault();
                    }

                    if(window.plugins&&window.plugins.umengAnalyticsPlugin){
                        //初始化友盟统计配置
                        window.plugins.umengAnalyticsPlugin.init();
                        //调试模式
                        window.plugins.umengAnalyticsPlugin.setDebugMode(true);
                    }
                    /* android 结束*/
                } else if(isiOS){
                    /* ios 开始*/
                    if (window.cordova && window.cordova.plugins.Keyboard) {
                        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                    }
                    if (window.StatusBar) {
                        // org.apache.cordova.statusbar required
                        StatusBar.styleDefault();
                    }
                    //初始化友盟统计
                    window.plugins.umengAnalyticsPlugin.init();
                    /* ios 结束*/
                }
                //注意，这段代码是应用退出前保存统计数据，请在退出应用前调用
                //window.plugins.umengAnalyticsPlugin.onKillProcess();
            });
            
            
        }])
/* 自动更新插件*/
.run(function($ionicPlatform, $http, $rootScope, $ionicActionSheet, $timeout, $cordovaAppVersion,  
        $ionicPopup, $ionicLoading, $cordovaFileTransfer, $cordovaFile, $cordovaFileOpener2) {  
    $ionicPlatform.ready(function() {  
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard  
        // for form inputs)  
        var u = navigator.userAgent;
        //console.log(navigator.userAgent);
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        console.log('是否是Android：'+isAndroid);
        console.log('是否是iOS：'+isiOS);

        if (window.cordova && window.cordova.plugins.Keyboard) {  
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);  
        };  
        if (window.StatusBar) {  
            StatusBar.styleDefault();  
        };  
        if(isAndroid){
            //服务器上保存版本信息
            $http.get(window.localStorage.base_url+'/app/config/appVersion')  
            .then(function(data){  
                var serverAppVersion = data.data.appVersion;//服务器 版本  
                //console.log("====>>服务器"+serverAppVersion);  
                if(window.cordova){
                    $cordovaAppVersion.getVersionNumber().then(function(version) {  
                        console.log("version=====本机>>>"+version+"====>>服务器"+serverAppVersion);  
                        if (version != serverAppVersion) {  
                            $ionicLoading.show({  
                                template: "已经下载：0%"  
                            });  
                            var url = "http://www.tr008.com/download/jinfabao.apk";   
                            var targetPath = "file:///mnt/sdcard/Download/jinfabao.apk";   
                            var trustHosts = true  
                            var options = {};  
                            $cordovaFileTransfer.download(url, targetPath, options, trustHosts).then(function (result) {  
                                $cordovaFileOpener2.open(targetPath, 'application/vnd.android.package-archive'  
                                ).then(function () {  
                                    }, function (err) {  
                                    });  
                                $ionicLoading.hide();  
                            }, function (err) {  
                                console.log(err);
                                alert('下载失败');
                                $ionicLoading.hide();   
                            }, function (progress) {                             
                                $timeout(function () {  
                                    var downloadProgress = (progress.loaded / progress.total) * 100;  
                                    $ionicLoading.show({  
                                        template: "已经下载：" + Math.floor(downloadProgress) + "%"  
                                    });  
                                    if (downloadProgress > 99) {  
                                        $ionicLoading.hide();  
                                    }  
                                })  
                            });  
                        }  
                    });  
                }
            }); 
        }
         
    });  
      
})
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
    // 解决底部导航在android手机顶部的问题
    $ionicConfigProvider.platform.ios.tabs.style('standard');
    $ionicConfigProvider.platform.ios.tabs.position('bottom');
    $ionicConfigProvider.platform.android.tabs.style('standard');
    $ionicConfigProvider.platform.android.tabs.position('bottom');
    $ionicConfigProvider.platform.ios.backButton.previousTitleText(false).icon('ion-chevron-left');
    $ionicConfigProvider.platform.android.backButton.previousTitleText(false).icon('ion-chevron-left'); 
    $ionicConfigProvider.backButton.text('返回');
    $ionicConfigProvider.platform.android.views.transition('android');
    $ionicConfigProvider.platform.ios.views.transition('ios');

    // 解决header标题在android手机不居中的问题
    $ionicConfigProvider.platform.ios.navBar.alignTitle('center');
    $ionicConfigProvider.platform.android.navBar.alignTitle('center');

    // Ionic uses AngularUI Router which uses the concept of states
    // Learn more here: https://github.com/angular-ui/ui-router
    // Set up the various states which the app can be in.
    // Each state's controller can be found in controllers.js
    $stateProvider

    // setup an abstract state for the tabs directive
    .state('web', {
        url: '/web',
        abstract: true,
        templateUrl: 'templates/tab/tabs.html'
    })

    // 分析与咨询tab
    .state('web.counsel-index', {
        cache: false,
        url: '/counsel/index',
        views: {
            'counsel-index': {
                templateUrl: 'templates/counsel/index.html',
                controller: 'CounselController'
            }
        }
    })

    .state('counsel-product-detail', {
        cache: false,
        url: '/counsel/product-detail',
        templateUrl: 'templates/counsel/product_detail.html',
        controller: 'TzfxPdetailController'
    })

    .state('counsel-tzfx', {
        cache: false,
        url: '/counsel/tzfx',
        templateUrl: 'templates/counsel/tzfx.html',
        controller: 'TzfxController'
    })

    .state('counsel-tzfx-ptype', {
        cache: false,
        url: '/counsel/tzfx-ptype',
        templateUrl: 'templates/counsel/tzfx_ptype.html',
        controller: 'TzfxController'
    })

    .state('web.counsel-contactway', {
        cache: false,
        url: '/counsel/contactway',
        views: {
            'counsel-index': {
                templateUrl: 'templates/counsel/contactway.html',
                controller: 'CounselController'
            }
        }
    })

    .state('counsel-lcgh', {
        cache: false,
        url: '/counsel/lcgh',
        templateUrl: 'templates/counsel/lcgh.html',
        controller: 'LcghController'
    }) 
    .state('counsel-lcgh1', {
        cache: false,
        url: '/counsel/lcgh1',
        templateUrl: 'templates/counsel/lcgh1.html',
        controller: 'LcghController'
    })    

    .state('counsel-lcgh2', {
        cache: false,
        url: '/counsel/lcgh2',
        templateUrl: 'templates/counsel/lcgh2.html',
        controller: 'LcghController'
    })

    .state('counsel-lcgh3', {
        cache: false,
        url: '/counsel/lcgh3',
        templateUrl: 'templates/counsel/lcgh3.html',
        controller: 'LcghController'
    })
    .state('counsel-lcgh4', {
        cache: false,
        url: '/counsel/lcgh4',
        templateUrl: 'templates/counsel/lcgh4.html',
        controller: 'LcghController'
    })
    .state('counsel-lcgh5', {
        cache: false,
        url: '/counsel/lcgh5',
        templateUrl: 'templates/counsel/lcgh5.html',
        controller: 'LcghController'
    })
    .state('counsel-lcgh6', {
        cache: false,
        url: '/counsel/lcgh6',
        templateUrl: 'templates/counsel/lcgh6.html',
        controller: 'LcghController'
    })
    .state('counsel-lcgh7', {
        cache: false,
        url: '/counsel/lcgh7',
        templateUrl: 'templates/counsel/lcgh7.html',
        controller: 'LcghController'
    })
    .state('counsel-lcgh8', {
        cache: false,
        url: '/counsel/lcgh8',
        templateUrl: 'templates/counsel/lcgh8.html',
        controller: 'LcghController'
    })
    .state('counsel-lcgh9', {
        cache: false,
        url: '/counsel/lcgh9',
        templateUrl: 'templates/counsel/lcgh9.html',
        controller: 'LcghController'
    })
    .state('counsel-lcgh10', {
        cache: false,
        url: '/counsel/lcgh10',
        templateUrl: 'templates/counsel/lcgh10.html',
        controller: 'LcghController'
    })

    .state('counsel-law', {
        cache: false,
        url: '/counsel/law',
        templateUrl: 'templates/counsel/law.html',
        controller: 'LawController'
    })

    .state('counsel-law-location', {
        cache: false,
        url: '/counsel/law-location?:city:choose',
        templateUrl: 'templates/counsel/law_location.html',
        controller: 'LawController'
    })

    .state('counsel-law-type', {
        cache: false,
        url: '/counsel/law-type',
        templateUrl: 'templates/counsel/law_type.html',
        controller: 'LawController'
    })

    .state('counsel-law-data', {
        cache: false,
        url: '/counsel/law-data',
        templateUrl: 'templates/counsel/law_data.html',
        controller: 'lawDataController'
    })

    // 理财精品tab
    .state('web.product-index', {
        cache: false,
        url: '/product/index',
        views: {
            'product-index': {
                templateUrl: 'templates/product/index.html',
                controller: 'ProductIndexController'
            }
        }
    })

    .state('products', {
        cache: false,
        url: '/products/:moduleId',
        templateUrl: 'templates/product/products.html',
        controller: 'ProductsController'
    })

    .state('product-detail', {
        cache: false,
        url: '/product/:id',
        templateUrl: 'templates/product/detail.html',
        controller: 'ProductDetailController'
    })

    .state('product-detail-intro', {
        cache: false,
        url: '/product/:id&intro',
        templateUrl: 'templates/product/detail-intro.html',
        controller: 'ProductDetailController'
    })

    .state('product-detail-riskc', {
        cache: false,
        url: '/product/:id&riskc',
        templateUrl: 'templates/product/detail-riskc.html',
        controller: 'ProductDetailController'
    })

    .state('product-login', {
        cache: false,
        url: '/login?:p',
        templateUrl: 'templates/user/loginx.html',
        controller: 'LoginxController'
    })

    .state('counsel-login', {
        cache: false,
        url: '/login?:p',
        templateUrl: 'templates/user/loginx.html',
        controller: 'LoginxController'
    })

    .state('pay-index', {
        cache: false,
        url: '/pay/index/:id',
        templateUrl: 'templates/pay/index.html',
        controller: 'PayController'
    })

    .state('pay-bankverify', {
        cache: false,
        url: '/pay/bankverify',
        templateUrl: 'templates/pay/bankverify.html',
        controller: 'PayBankverifyController'                
    })

    .state('pay-voucher', {
        cache: false,
        url: '/pay/voucher',
        templateUrl: 'templates/pay/voucher.html',
        controller: 'PayVoucherController'
    })
    .state('pay-agreement', {
        cache: false,
        url: '/pay/agreement/:id',
        templateUrl: 'templates/pay/agreement.html',
        controller: 'agreementController'
    })
    .state('payment', {
        cache: false,
        url: '/pay/payment',
        templateUrl: 'templates/pay/payment.html',
        controller: 'PaymentController'
    })

    // 个人实名验证 
    .state('user-auth', {
        cache: false,
        url: '/user/auth',
        templateUrl: 'templates/user/real_name_auth.html',
        controller: 'UserController'
    })

    .state('user-set-trade-password', {
        cache: false,
        url: '/user/set-trade-password',
        templateUrl: 'templates/user/set_trade_password.html',
        controller: 'UserController'
    })

    //更多tab
    .state('web.more',{
        cache: false,
        url:'/more',
        views:{
            'more-index':{
                templateUrl:'templates/about/more.html',
                controller: 'UserIndexController'
            }
        }
    })
    //更多tab
    .state('web.user-index',{
        cache: false,
        url:'/user/index',
        views:{
            'user-index':{
                templateUrl:'templates/user/index.html',
                controller: 'UserIndexController'
            }
        }
    })

    .state('user-login',{
        cache: false,
        url:'/user/login',
                templateUrl:'templates/user/login.html',
                controller: 'UserLoginController'
    })

    .state('user-register',{
        cache: false,
        url:'/user/register',
        templateUrl:'templates/user/register.html',
        controller: 'UserRegisterController'
    })

    .state('user-password',{
        cache: false,
        url:'/user/password',
        templateUrl:'templates/user/password.html',
        controller: 'UserPasswordController'
    })
    .state('user-detail',{
        cache: false,
        url:'/user/detail',
        templateUrl:'templates/user/user_detail.html',
        controller: 'UserIndexController'
    })
    .state('user-modify-pwd',{
        cache: false,
        url:'/user/modifyPwd',
        templateUrl:'templates/user/modify_password.html',
        controller: 'UserIndexController'
    })
    .state('user-invite',{
        cache: false,
        url:'/user/invite',
        templateUrl:'templates/user/invite.html',
        controller: 'UserInviteController'
    })

    .state('user-asset-index', {
        cache: false,
        url: '/user/asset',
        templateUrl: 'templates/asset/index.html',
        controller: 'UserAssetController'
    })

    .state('user-asset-trhistory', {
        cache: false,
        url: '/user/asset/trhistory?:t',
        templateUrl: 'templates/asset/trhistory.html',
        controller: 'UserAssetController'
    })

    .state('user-asset-trhistoryall', {
        cache: false,
        url: '/user/asset/trhistoryall',
        templateUrl: 'templates/asset/trhistoryall.html',
        controller: 'UserAssetController'
    })

    .state('user-asset-return', {
        cache: false,
        url: '/user/asset/return',
        templateUrl: 'templates/asset/return.html',
        controller: 'UserAssetReturnController'
    })

    .state('user-asset-return-detail', {
        cache: false,
        url: '/user/asset/return?:id:state',
        templateUrl: 'templates/asset/returndetail.html',
        controller: 'UserAssetReturnDetailController'
    })

    .state('user-asset-dqb', {
        cache: false,
        url: '/asset/dqb',
        templateUrl: 'templates/asset/dqb.html',
        controller: 'UserAssetController'
    })

    .state('user-asset-hqb', {
        cache: false,
        url: '/asset/hqb',
        templateUrl: 'templates/asset/hqb.html',
        controller: 'UserAssetHqbController'
    })

    .state('user-asset-ttz', {
        cache: false,
        url: '/asset/ttz',
        templateUrl: 'templates/asset/ttz.html',
        controller: 'AssetController'
    })

    .state('user-asset-ttzdetail', {
        cache: false,
        url: '/asset/ttzdetail?:id',
        templateUrl: 'templates/asset/ttzdetail.html',
        controller: 'AssetController'
    })

    .state('user-asset-hqbdetail', {
        cache: false,
        url: '/asset/hqbdetail?:id:action',
        templateUrl: 'templates/asset/hqbdetail.html',
        controller: 'AssetHqbController'
    })

    .state('user-asset-dqbdetail', {
        cache: false,
        url: '/asset/dqbdetail?:id',
        templateUrl: 'templates/asset/dqbdetail.html',
        controller: 'AssetController'
    })
    .state('user-asset-trhistorydetail', {
        cache: false,
        url: '/asset/trhistorydetail?:id',
        templateUrl: 'templates/asset/trhistorydetail.html',
        controller: 'AssetController'
    })

    .state('user-asset-rollout', {
        cache: false,
        url: '/asset/rollout',
        templateUrl: 'templates/asset/rollout.html',
        controller: 'AssetController'
    })

    .state('user-bankcard', {
        cache: false,
        url: '/bankcard/index',
        templateUrl: 'templates/bankcard/index.html',
        controller: 'BankcardController'
    })

    .state('aboutus', {
        cache: false,
        url: '/aboutus',
        templateUrl: 'templates/about/aboutus.html'
    })

    .state('ensure', {
        cache: false,
        url: '/aboutus',
        templateUrl: 'templates/about/ensure.html'
    })

    .state('consul', {
        cache: false,
        url: '/consul',
        templateUrl: 'templates/user/consul.html',
        controller: 'ConsulController'
    })

    .state('consul-detail', {
        cache: false,
        url: '/consul/detail?:id:type',
        templateUrl: 'templates/user/consul_detail.html',
        controller: 'ConsulDetailController'
    })

    .state('voucher', {
        cache: false,
        url: '/voucher?:state',
        templateUrl: 'templates/user/voucher.html',
        controller: 'VoucherController'
    })

    .state('commonqa', {
        cache: false,
        url: '/commonqa',
        templateUrl: 'templates/about/commonqa.html'
    })

    .state('settings', {
        cache: false,
        url: '/settings',
        templateUrl: 'templates/about/settings.html'
    })

    .state('feedback', {
        cache: false,
        url: '/feedback',
        templateUrl: 'templates/about/feedback.html',
        controller: 'feedbackController'
    })

    .state('bankcard-add', {
        cache: false,
        url: '/bankcard/add',
        templateUrl: 'templates/bankcard/add_bankcard.html',
        controller: 'BankcardController'
    })

    .state('banklist', {
        cache: false,
        url: '/banklist',
        templateUrl: 'templates/bankcard/banklist.html',
        controller: 'BanklistController'
    })

    //活动与抽奖tab
    .state('web.activity-index', {
        cache: false,
        url: '/activity/index',
        views:{
            'activity-index': {
                templateUrl: 'templates/activity/index.html',
                controller: 'ActivityController'
            }
        }
    })

    .state('activity-aca', {
        cache: false,
        url: '/activity/aca',
        templateUrl: 'templates/activity/aca.html',
        controller: 'acaController'
    })
    .state('activity-acb', {
        cache: false,
        url: '/activity/acb',
        templateUrl: 'templates/activity/acb.html',
        controller: 'acbController'
    })
    .state('activity-acc', {
        cache: false,
        url: '/activity/acc',
        templateUrl: 'templates/activity/acc.html',
        controller: 'accController'
    })
    .state('activity-acd', {
        cache: false,
        url: '/activity/acd',
        templateUrl: 'templates/activity/acd.html',
        controller: 'acdController'
    })
    .state('activity-ace', {
        cache: false,
        url: '/activity/ace',
        templateUrl: 'templates/activity/ace.html',
        controller: 'aceController'
    })
    .state('order-index', {
        cache: false,
        url: '/order/index',
        templateUrl: 'templates/order/index.html',
        controller: 'OrderController'
    })

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/web/counsel/index');

});
